
<template>
  <div style="width: 100%">
    <el-form :inline="true" class="demo-form-inline">
      <el-form-item label="客户姓名：">
        <el-input v-model="customerName" placeholder="请输入客户姓名" />
      </el-form-item>
      <el-form-item label="身份证号：">
        <el-input v-model="idNumber" placeholder="请输入身份证号" />
      </el-form-item>
      <el-form-item label="合同号：">
        <el-input v-model="contractNumber" placeholder="请输入合同号" />
      </el-form-item>
      <el-form-item label="借据号：">
        <el-input v-model="loanNumber" placeholder="请输入借据号" />
      </el-form-item>
      <el-form-item style="margin-top: 40px; margin-left: -50px">
        <el-button
          type="primary"
          icon="el-icon-search"
          size="medium"
          @click="searchAll"
          >查询</el-button
        >
      </el-form-item>
      <el-form-item style="margin-top: 40px">
        <el-button
          type="primary"
          icon="el-icon-refresh-left"
          size="medium"
          @click="restAll"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <div style="padding-bottom: 10px; padding-top: 10px">
      <el-button icon="el-icon-refresh-right" size="mini" @click="handleRefresh"
        >刷新</el-button
      >
      <el-button icon="el-icon-s-data" size="mini" @click="openTrial"
        >试算</el-button
      >
      <el-button icon="el-icon-s-data" size="mini" @click="openaccount"
        >开户</el-button
      >
    </div>
    <!--客户借据信息-->
    <el-table
      :data="loanData"
      title="客户借据信息"
      border
      height="250"
      stripe="true"
      style="width: 100%"
      @row-dblclick="showRepaymentPlan"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" :selectable="selectable" />
      <el-table-column
        prop="billNo"
        label="借据号"
        width="100"
        align="center"
      />
      <el-table-column
        prop="contrNo"
        label="合同号"
        width="120"
        align="center"
      />
      <el-table-column prop="name" label="姓名" width="80" align="center" />
      <el-table-column
        prop="idNo"
        label="身份证号"
        width="180"
        align="center"
      />
      <el-table-column
        prop="virAcctNo"
        label="线下还款账户"
        width="200"
        align="center"
      />
      <el-table-column
        prop="loanProdGroup"
        label="贷款产品组"
        width="100"
        align="center"
      />
      <el-table-column
        prop="loanCode"
        label="产品代码"
        width="100"
        align="center"
      />
      <el-table-column
        prop="loanPrin"
        label="放款金额"
        width="100"
        align="center"
      />
      <el-table-column
        prop="setupDate"
        label="放款日期"
        width="105"
        align="center"
      />
      <el-table-column
        prop="origLoanTerm"
        label="放款期数"
        width="100"
        align="center"
      />
      <el-table-column
        prop="nextStmtDate"
        label="下个还款日"
        width="100"
        align="center"
      />
    </el-table>
    <!-- <el-pagination
      background
      layout="prev, pager, next"
      :total="total"
      style="float:left;margin-top: 10px;"
      @prev-click="prevClick"
      @next-click="nextClick"
      @current-change="handleCurrentChange"
    /> -->

    <div style="margin-top: 56px">
      <el-tabs v-model="activeTab" type="card" editable @edit="closeTab">
        <el-tab-pane
          v-for="(tab, index) in tabList"
          :key="tab.name"
          :name="tab.name"
          :label="tab.label"
        >
          <!-- 还款计划信息组件 -->
          <RepaymentPlan :rowData="rowData" />
        </el-tab-pane>
      </el-tabs>
    </div>
    <!-- 试算 页面 -->
    <div>
      <el-dialog
        title="试算页面"
        :visible.sync="trialDialogVisible"
        :before-close="handleTrialDialogClose"
        width="80%"
        top="4vh"
      >
        <el-form :label-position="left" label-width="120px" :model="trialForm">
          <el-form-item label="还款方式：">
            <el-select
              v-model="offlinePayMode"
              placeholder="请选择"
              clearable="true"
              style="width: 100%"
            >
              <el-option
                v-for="item in offlinePayModes"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="预计还款日期：">
            <el-date-picker
              v-model="confirmDate"
              align="right"
              type="date"
              placeholder="选择日期"
              :picker-options="pickerOptions"
              value-format="yyyy-MM-dd"
              style="width: 100%"
            />
          </el-form-item>
          <p style="color: red">
            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;员工贷产品不支持还款日提前结清，请提示客户，避免出现入账失败情况
          </p>
          <el-form-item>
            <!-- 确认按钮 -->
            <div style="text-align: center">
              <el-button
                round
                type="primary"
                icon="el-icon-edit"
                size="mini"
                @click="Confirm"
                :disabled="dis_confirm"
                >确认</el-button
              >
            </div>
          </el-form-item>

          <el-form-item label="借据号">
            <el-input v-model="trialData.billNo" :disabled="true" />
          </el-form-item>
          <el-form-item label="合同号">
            <el-input v-model="trialData.contrNo" :disabled="true" />
          </el-form-item>
          <el-form-item label="姓名">
            <el-input v-model="trialData.customerName" :disabled="true" />
          </el-form-item>
          <el-form-item label="证件号码">
            <el-input v-model="trialData.idNo" :disabled="true" />
          </el-form-item>
          <el-form-item label="线下还款账户号">
            <el-input v-model="trialData.virAcctNo" :disabled="true" />
          </el-form-item>
          <el-form-item label="还款类型">
            <el-input v-model="trialData.offRepayTypeTran" :disabled="true" />
          </el-form-item>
          <el-form-item label="还款金额">
            <el-input v-model="trialData.repayAmt" :disabled="true" />
          </el-form-item>

          <el-form-item>
            <!-- 试算按钮 -->
            <div style="text-align: center">
              <el-button
                round
                type="primary"
                icon="el-icon-s-data"
                size="mini"
                @click="handleTrial"
                :disabled="dis_Trial"
                >试算</el-button
              >
            </div>
          </el-form-item>

          <el-form-item label="应还金额">
            <el-input v-model="loanAmt.loanTermAmt" :disabled="true" />
          </el-form-item>
          <el-form-item label="应还本金">
            <el-input v-model="loanAmt.loanTermPrin" :disabled="true" />
          </el-form-item>
          <el-form-item label="应还利息">
            <el-input v-model="loanAmt.loanTermInt" :disabled="true" />
          </el-form-item>
          <el-form-item label="应还罚息">
            <el-input v-model="loanAmt.loanTermPen" :disabled="true" />
          </el-form-item>
          <el-form-item label="应还担保费">
            <el-input v-model="loanAmt.loanTermFee" :disabled="true" />
          </el-form-item>
          <el-form-item label="应还违约金">
            <el-input v-model="loanAmt.loanFee" :disabled="true" />
          </el-form-item>

          <el-form-item>
            <!-- 返回按钮 -->
            <div style="text-align: center">
              <el-button
                type="primary"
                icon="el-icon-caret-left"
                size="mini"
                round
                @click="handleTrialDialogClose"
                >返回</el-button
              >
            </div>
          </el-form-item>
        </el-form>
      </el-dialog>
    </div>
  </div>
</template>


<script>
import RepaymentPlan from "@/views/data/repaymentPlan";
import {
  offlineRepaymentApplyForAccount,
  tnqContractDetailList,
} from "@/api/interface";
export default {
  components: {
    RepaymentPlan,
  },
  data() {
    return {
      customerName: "",
      contractNumber: "",
      loanNumber: "",
      idNumber: "",
      pageSize: 10,
      pageNo: 1,
      total: 100,
      //loanData: [{contrNo:'1111'}],
      loanData: [
        // {
        //   productName: "信也",
        //   productCode: "6012-信也-智云担保",
        //   loanNumber: "123456",
        //   contractNumber: "789012",
        //   idNo: "1234567890",
        //   customerName: "张三",
        //   applyDate: "2022-01-01",
        //   loanStatus: "已放款",
        //   customerInfo: {
        //     khbh: "cs111",
        //     zjlx: "sfz",
        //     cardNo: "1111111",
        //     xm: "cs",
        //     mobileNo: "12345677",
        //     cardNo: "123456788",
        //   },
        //   loanInfo: {
        //     khxm: "11111111",
        //   },
        //   scheduleInfo: {
        //     ksrq: "11111",
        //   },
        //   repayDetail: {
        //     zwrq: "111111",
        //   },
        // },
      ],
      dialogVisible: false,
      repaymentPlan: [{ currentPeriod: 1 }],
      activeTab: "",
      tabList: [],
      rowData: [],
      dis_confirm: false,
      dis_Trial: false,
      isshowRepaymentPlan: false,
      key: 0,
      selectedRow: [],
      trialDialogVisible: false,
      trialData: {},
      trialForm: {},
      loanAmt: {},

      offlinePayModes: [
        {
          value: "NORMAL_REPAY",
          label: "正常还款",
        },
        {
          value: "PRE_SETTLE",
          label: "提前结清",
        },
      ],
      offlinePayMode: "",
      confirmDate: null,
      pickerOptions: {
        shortcuts: [
          {
            text: "今天",
            onClick(picker) {
              picker.$emit("pick", new Date());
            },
          },
          {
            text: "昨天",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24);
              picker.$emit("pick", date);
            },
          },
          {
            text: "一周前",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", date);
            },
          },
        ],
      },
    };
  },

  created() {
    console.log("借据详情初始化");
    var queryData = {
      customerName: "",
      idNumber: "",
      contractNumber: "",
      loanNumber: "",
    };
    console.log(JSON.parse(sessionStorage.getItem("personalInfoData")));
    queryData.customerName = JSON.parse(
      sessionStorage.getItem("personalInfoData")
    ).custName;
    queryData.idNumber = JSON.parse(
      sessionStorage.getItem("personalInfoData")
    ).idNo;
    queryData.contractNumber =
      JSON.parse(sessionStorage.getItem("personalInfoData")).contractNumber ||
      "";
    queryData.loanNumber =
      JSON.parse(sessionStorage.getItem("personalInfoData")).loanNumber || "";

    console.log("线下还款初始化入参", queryData);
    this.queryLoan(queryData);
  },

  watch: {
    $route: function (to, from) {
      console.log("监听【线下还款模块】route变化");
      this.$destroy();
    },
  },

  methods: {
    // 根据客户姓名、合同号、借据号、身份证号查询客户借据信息（客户姓名和身份证号必须绑定在一起传入后台，合同号、借据号可任意输入）
    searchAll() {
      var str =
        this.customerName +
        this.idNumber +
        this.contractNumber +
        this.loanNumber;
      if (str.length === 0) {
        window.globalUiKit.notify(
          "提示",
          "请至少输入客户姓名、合同号、身特证号、借据号中的一项",
          "error"
        );
        return;
      }
      var str2 = this.customerName + this.idNumber;
      if (str2.length > 0) {
        if (!(this.customerName && this.idNumber)) {
          window.globalUiKit.notify(
            "提示",
            "客户姓名与身份证号必须一起输入",
            "error"
          );
          return;
        }
      }
      console.log("开始查询客户借据信息=========");
      var queryData = {};
      queryData.contractNumber = this.contractNumber; //合同号
      queryData.customerName = this.customerName; //姓名
      queryData.idNumber = this.idNumber; //身份证号
      queryData.loanNumber = this.loanNumber; //借据号
      // queryData.pageSize = this.pageSize
      // queryData.pageNo = this.pageNo
      this.queryLoan(queryData);
      console.log("查询客户借据信息结束=========");
    },
    queryLoan(queryData) {
      console.log("查询入参", queryData);
      console.log("调用核心系统借据详情查询接口--------");

      axios
        .post(
          window.CONFIG.tradingUrl + "/OfflineRepayment/getLoanInfo",
          queryData
        )
        .then((res) => {
          console.log("借据信息查询结果：");
          console.log(res);
          if (res.data.status == "true") {
            // 返回信息处理：
            this.loanData = res.data.data;
            if (res.data.data.length > 0) {
              window.globalUiKit.notify("提示", "借据信息查询成功", "success");
            } else {
              window.globalUiKit.notify(
                "提示",
                "未查询到相关借据信息，请联系管理员",
                "info"
              );
            }
          } else {
            this.loanData = [];
            window.globalUiKit.notify(
              "提示",
              "未查询到相关借据信息，请联系管理员",
              "info"
            );
            console.log("查询借据信息未成功：");
          }
        });

      // tnqContractDetailList(queryData).then((res) => {
      //   console.log("借据信息返回数据==", res);
      //   if (res.data.code == "200") {
      //     this.loanData = res.data.data;
      //   } else {
      //     this.loanData = [];
      //     window.globalUiKit.notify("提示", res.data.message, "info");
      //   }
      // });
    },

    // 重置搜索框和列表
    restAll() {
      console.log("重置 客户借据信息列表=======");
      this.customerName = "";
      this.contractNumber = "";
      this.loanNumber = "";
      this.idNumber = "";
      // this.loanData = [];
      //this.pageNo = 1
    },

    // 展示还款计划明细
    showRepaymentPlan(row) {
      this.rowData = row.scheduleInfoList;

      // 根据借据信息调用核心系统接口查询还款计划明细
      // 创建tab页
      const newTab = {
        label: `还款计划 - ${row.contrNo}`, // 使用借据信息中的唯一标识作为tab标题
        name: row.contrNo.toString(),
        data: row, // 传递借据信息数据到新页
        component: "RepaymentPlan", // 添加组件名称
      };

      // 跳转tab页
      this.tabList.push(newTab);

      // 固定新打开的tab页
      this.activeTab = row.contrNo.toString();

      //
    },

    // 上一页
    prevClick() {
      this.pageNo = this.pageNo - 1;
      // this.showTable();
    },
    // 下一页
    nextClick() {
      this.pageNo = this.pageNo + 1;
      // this.showTable();
    },
    // 当前页
    handleCurrentChange(val) {
      this.pageNo = val;
      // this.showTable();
    },

    // tab页标签关闭按钮
    closeTab(targetName, action) {
      const tabs = this.tabList;
      let activeName = this.activeTab;
      if (activeName === targetName) {
        tabs.forEach((tab, index) => {
          if (tab.name === targetName) {
            const nextTab = tabs[index + 1] || tabs[index - 1];
            if (nextTab) {
              activeName = nextTab.name;
            }
          }
        });
      }
      this.activeTab = activeName;
      this.tabList = tabs.filter((tab) => tab.name !== targetName);
    },

    // 当选择项发生变化时，赋值选中行数据selectedRow
    handleSelectionChange(val) {
      this.selectedRow = val;
    },
    //开户
    openaccount() {
      // console.log("选中的借据信息==", this.selectedRow);

      if (this.$store.getters.GET_OFFLINESTATUS) {
        return window.globalUiKit.notify("提示", "离线状态不能开户！", "error");
      }

      if (this.selectedRow.length === 0) {
        return window.globalUiKit.notify("提示", "请选择一条借据信息", "error");
      } else if (this.selectedRow.length > 1) {
        return window.globalUiKit.notify(
          "提示",
          "最多只能选择一条借据信息",
          "error"
        );
      }

      var params = {
        //入参为当前选中借据的信息
        contrNbr: this.selectedRow[0].contrNo,
      };

      //触发开户
      // console.log("触发开户,入参==", params);
      offlineRepaymentApplyForAccount(params).then((res) => {
        console.log("开户信息返回==", res);
        if (res.data.status == true) {
          window.globalUiKit.notify("提示", res.data.msg, "info");
        } else {
          window.globalUiKit.notify("提示", res.data.msg, "info");
        }
      });
    },

    // 进入试算页面按钮
    openTrial() {
      console.log("进入试算页面：");
      console.log(this.dis_confirm);
      console.log(this.selectedRow);
      if (this.selectedRow.length === 0) {
        window.globalUiKit.notify("提示", "请选择一条借据信息", "error");
        return;
      }
      if (this.selectedRow.length > 1) {
        window.globalUiKit.notify(
          "提示",
          "试算只能选择一行数据，请重新选择",
          "error"
        );
        return;
      }
      // 将选中的借据信息赋值给试算页面的表单数据
      this.trialData.billNo = this.selectedRow[0].billNo;
      this.trialData.contrNo = this.selectedRow[0].contrNo;
      this.trialData.customerName = this.selectedRow[0].name;
      this.trialData.idNo = this.selectedRow[0].idNo;
      this.trialData.virAcctNo = this.selectedRow[0].virAcctNo;
      this.trialData.offRepayType = ""; // 还款类型
      this.trialData.offRepayTypeTran = ""; // 还款类型(输入框)

      this.trialDialogVisible = true;
    },
    // 刷新借据信息表格
    handleRefresh() {
      this.loanData = [];
    },

    // 试算页面 确认按钮
    Confirm() {
      console.log("============== 试算还款类型：==============");
      if (
        this.offlinePayMode !== "" &&
        this.confirmDate !== null &&
        this.trialData.contrNo !== undefined
      ) {
        var resData = {};
        resData.offlinePayMode = this.offlinePayMode;
        resData.confirmDate = this.confirmDate;
        resData.offRepayType = this.trialData.offRepayType;
        resData.contrNo = this.trialData.contrNo;

        this.toTrail(resData);
      } else {
        window.globalUiKit.notify(
          "提示",
          "请输入还款方式、预计还款日期、合同号",
          "error"
        );
        return;
      }
      console.log("============== 试算还款类型结束：==============");
    },

    // 试算页面 试算按钮
    handleTrial() {
      console.log(
        "==================== 开始进行试算金额：===================="
      );

      if (
        this.trialData.offRepayType !== "" &&
        this.confirmDate !== null &&
        this.trialData.contrNo !== undefined
      ) {
        var resData = {};
        resData.offRepayType = this.trialData.offRepayType;
        resData.confirmDate = this.confirmDate;
        resData.repayAmt = this.trialData.repayAmt;
        resData.contrNo = this.trialData.contrNo;
        this.toTrail(resData);

        console.log("==================== 试算金额结束：====================");
      } else {
        window.globalUiKit.notify(
          "提示",
          "请检查还款类型、预计还款日期、合同号",
          "error"
        );
        return;
      }
    },

    toTrail(resData) {
      axios
        .post(
          window.CONFIG.tradingUrl + "/OfflineRepayment/offlineRepayTrial",
          resData
        )
        .then((res) => {
          console.log("线下还款试算【还款金额】返回结果：");
          console.log(res);
          if (res.data.status == "true") {
            // 返回信息处理：
            if (res.data.data.respType !== null) {
              console.log("线下还款试算【还款类型】成功");
              var type = res.data.data.respType;
              this.trialData.offRepayType = type;
              console.log(this.trialData.offRepayType);
              if (type == "OVERDUE_REPAY") {
                this.trialData.offRepayTypeTran = "逾期还款";
              } else if (type == "NORMAL_REPAY") {
                this.trialData.offRepayTypeTran = "正常还款";
              } else if (type == "OVERDUE_PRE_SETTLE") {
                this.trialData.offRepayTypeTran = "逾期结清";
              } else if (type == "PRE_SETTLE") {
                this.trialData.offRepayTypeTran = "提前结清";
              } else {
                console.log(
                  "还款类型：" + res.data.data.respType + " ,请联系管理员"
                );
              }
              this.dis_confirm = true;
            }

            if ("respAmtObj" in res.data.data) {
              console.log("线下还款试算【还款金额】成功");
              var respAmtObj = res.data.data.respAmtObj;
              this.loanAmt.loanTermAmt = respAmtObj.loanTermAmt; //应还金额
              this.loanAmt.loanTermPrin = respAmtObj.loanTermPrin; //应还本金
              this.loanAmt.loanTermInt = respAmtObj.loanTermInt; //应还利息
              this.loanAmt.loanTermPen = respAmtObj.loanTermPen; //应还罚息
              this.loanAmt.loanTermFee = respAmtObj.loanTermFee; //应还担保费
              this.loanAmt.loanFee = respAmtObj.loanFee; //应还违约金

              console.log(this.trialData);
              this.$set(this.loanAmt, this.loanAmt);
              this.dis_Trial = true;
            }

            this.$set(this.trialData, this.trialData);
          } else {
            window.globalUiKit.notify(
              "提示",
              "没有查询到相关信息，请联系管理员",
              "error"
            );
            return;
          }
        });
    },

    // 关闭试算Dialog前的回调，会暂停 Dialog 的关闭（关闭试算页面的逻辑处理）
    handleTrialDialogClose() {
      this.trialDialogVisible = false;
      //重置试算列表和还款方式、提前还款日期表单
      this.trialData = {};
      this.offlinePayMode = "";
      this.confirmDate = "";
      this.loanAmt = {};
      this.dis_confirm = false;
      this.dis_Trial = false;
    },
  },
};
</script>
